package com.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import test.demo.db.StaffOperation;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String NAME_PARAMETER = "user_name";
	private static final String PASSWORD_PARAMETER = "password";
	private static final String NAME_OR_PASSWORD_ERROR = "name or password error!!!";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String name = req.getParameter(NAME_PARAMETER);
			String password = req.getParameter(PASSWORD_PARAMETER);
			StaffOperation operation = StaffOperation.getInstance();
			if (operation.checkStaff(name, password)) {
				req.getSession().setAttribute("session_name",name);
				resp.sendRedirect("punchCard.jsp");
			} else {
				req.setAttribute("message", NAME_OR_PASSWORD_ERROR);
				req.getRequestDispatcher("login.jsp").forward(req, resp);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

}
